// 获取所有导航链接
const navLinks = document.querySelectorAll('.nav-link');
// 获取所有内容区域
const contents = document.querySelectorAll('.content');
// 获取编辑/添加教室内容区域的表格（假设在其他地方已经正确获取到了，这里保留代码结构）
const classroomTable = document.getElementById('classroomTable');

// 为每个导航链接添加点击事件处理函数
navLinks.forEach((link) => {
    link.addEventListener('click', function (e) {
        e.preventDefault();

        // 移除所有导航链接的 active 类
        navLinks.forEach((navLink) => {
            navLink.classList.remove('active');
        });

        // 添加当前点击链接的 active 类
        this.classList.add('active');

        // 隐藏所有内容区域
        contents.forEach((content) => {
            content.classList.remove('active');
            content.style.display = 'none';
        });

        // 获取目标内容区域的ID
        const targetId = this.dataset.target;

        // 根据ID查找目标内容区域
        const target = document.getElementById(targetId);

        if (target) {
            // 如果找到了目标内容区域，则添加active类并显示出来
            target.classList.add('active');
            target.style.display = 'block';

            // 根据点击的不同标签，向后端发送对应请求（这里保留你原始代码中的请求逻辑部分，省略详细展开）
            switch (targetId) {
                case 'content1':
                    // 发送请求获取编辑/添加教室的数据（这里省略具体的fetch请求及后续处理逻辑，因为你说不需要改动这部分，只关注显示隐藏功能）
                    fetch('SearchAllClassrooms')
                        .then((response) => {
                            if (!response.ok) {
                                throw new Error('Network response was not ok');
                            }
                            return response.json();
                        })
                        .then((data) => {
                            // 清空表格现有内容
                            const tableBody = classroomTable.querySelector('tbody');
                            tableBody.innerHTML = '';

                            // 遍历数据并添加到表格中
                            data.forEach((classroom) => {
                                const row = document.createElement('tr');
                                const classroomIdCell = document.createElement('td');
                                classroomIdCell.textContent = classroom.classroomId;
                                const classroomNameCell = document.createElement('td');
                                classroomNameCell.textContent = classroom.classroomName;
                                const capacityCell = document.createElement('td');
                                capacityCell.textContent = classroom.capacity;
                                const descriptionCell = document.createElement('td');
                                descriptionCell.textContent = classroom.description;
                                const statusCell = document.createElement('td');
                                statusCell.textContent = classroom.status;
                                const locationCell = document.createElement('td');
                                locationCell.textContent = classroom.location;

                                const editButton = document.createElement('button');
                                editButton.className = 'editButton';
                                editButton.dataset.classroomId = classroom.classroomId;
                                editButton.textContent = '编辑';

                                // 为编辑按钮添加点击事件处理程序，修改为跳转到编辑页面并传递数据
                                editButton.addEventListener('click', function () {
                                    const classroomId = this.dataset.classroomId;
                                    // 先获取当前行的数据
                                    const currentRow = this.closest('tr');
                                    const classroomName = currentRow.querySelector('td:nth-child(2)').textContent;
                                    const capacity = currentRow.querySelector('td:nth-child(3)').textContent;
                                    const description = currentRow.querySelector('td:nth-child(4)').textContent;
                                    const status = currentRow.querySelector('td:nth-child(5)').textContent;
                                    const location = currentRow.querySelector('td:nth-child(6)').textContent;

                                    // 构建要传递到编辑页面的查询参数
                                    const queryParams = {
                                        classroomId: classroomId,
                                        classroomName: classroomName,
                                        capacity: capacity,
                                        description: description,
                                        status: status,
                                        location: location
                                    };

                                    // 将查询参数转换为URL编码的字符串形式
                                    const queryString = Object.keys(queryParams).map(key => `${key}=${encodeURIComponent(queryParams[key])}`).join('&');

                                    // 跳转到编辑页面，并将查询参数添加到URL后面
                                    window.location.href = `edit?${queryString}`;
                                });

                                const deleteButton = document.createElement('button');
                                deleteButton.className = 'deleteButton';
                                deleteButton.dataset.classroomId = classroom.classroomId;
                                deleteButton.textContent = '删除';

                                // 为删除按钮添加点击事件处理程序
                                deleteButton.addEventListener('click', function () {
                                    const classroomId = this.dataset.classroomId;

                                    // 使用alert弹窗进行确认删除提示
                                    if (confirm('你确定要删除教室编号为' + classroomId + '的教室吗？')) {
                                        // 发送DELETE请求到后端删除教室信息（假设后端接口为/deleteClassroom）
                                        const deleteUrl = 'deleteClassroom?classroomId=' + classroomId;
                                        fetch(deleteUrl)
                                            .then((response) => {
                                                if (!response.ok) {
                                                    throw new Error('Network response was not ok');
                                                }
                                                return response.text();
                                            })
                                            .then((message) => {
                                                if (message) {
                                                    alert('教室删除成功');
                                                    // 重新获取数据并刷新表格显示（可优化为只更新当前行数据）
                                                    const currentRow = this.closest('tr');
                                                    if (currentRow) {
                                                        currentRow.remove();
                                                    }
                                                } else {
                                                    alert('教室删除失败!');
                                                }
                                            })
                                            .catch((error) => {
                                                console.error('删除请求出错：', error);
                                                alert('删除请求出错，请稍后重试');
                                            });
                                    }
                                });

                                const operationCell = document.createElement('td');
                                operationCell.appendChild(editButton);
                                operationCell.appendChild(deleteButton);

                                row.appendChild(classroomIdCell);
                                row.appendChild(classroomNameCell);
                                row.appendChild(capacityCell);
                                row.appendChild(descriptionCell);
                                row.appendChild(statusCell);
                                row.appendChild(locationCell);
                                row.appendChild(operationCell);

                                tableBody.appendChild(row);
                            });

                        })
                        .catch((error) => {
                            console.error('获取编辑/添加教室数据时出错：', error);
                        });
                    break;
                case 'content2':
                    // 这里可以添加点击删除教室导航链接后的相关逻辑，比如发送请求获取要删除的教室列表等（同样省略具体逻辑）
                    // 获取表单元素
                    const form = document.querySelector('#addclassrooms form');

                    // 为表单的提交事件添加监听器
                    form.addEventListener('submit', function (e) {
                        e.preventDefault();

                        // 获取表单数据
                        const classroomData = {
                                        classroomId: form.elements['classroomId'].value,
                                classroomName: form.elements['classroomName'].value,
                                    capacity: parseInt(form.elements['capacity'].value),
                                    description: form.elements['description'].value,
                                   status: form.elements['status'].value,
                                    location: form.elements['location'].value
                              };
                        console.log("获取到的表单数据：", classroomData);
                        // 使用fetch发送GET请求
                        fetch('addclassroom', {
                            method: 'POST',
                            body: JSON.stringify(classroomData),
                            "Content-Type":"application/json"
                        })
                            .then((response) => {
                                if (!response.ok) {
                                    throw new Error('Network response was not ok');
                                }
                                return response.text();
                            })
                            .then((message) => {
                                if (message === 'success') {
                                    alert('添加教室信息成功');
                                } else {
                                    alert('添加教室信息失败: ' + message);
                                }
                            })
                            .catch((error) => {
                                console.error('提交请求出错：', error);
                                alert('提交请求出错，请稍后重试');
                            });
                    });

                    break;
            }
            // 解析用户在prompt中输入的编辑后信息的函数
            function parseEditedData(editedInfo) {
                const lines = editedInfo.split('\n');
                const editedData = {
                    classroomName: '',
                    capacity: '',
                    description: '',
                    status: '',
                    location: ''
                };

                return editedData;
            }
        }
    });
});